<template>
  <div class="event-bus-demo">
    <!-- 组件A -->
    <div class="component-a">
      <h4>组件A</h4>
      <div class="component-content">
        <p>收到的消息: {{ receivedMessageA }}</p>
        <el-input v-model="messageA" placeholder="输入消息">
          <template #append>
            <el-button @click="sendMessageA">发送给组件B</el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 组件B -->
    <div class="component-b">
      <h4>组件B</h4>
      <div class="component-content">
        <p>收到的消息: {{ receivedMessageB }}</p>
        <el-input v-model="messageB" placeholder="输入消息">
          <template #append>
            <el-button @click="sendMessageB">发送给组件A</el-button>
          </template>
        </el-input>
      </div>
    </div>
  </div>
</template>

<script>
import EventBus from '@/utils/eventBus'

export default {
  name: 'EventBusDemo',
  
  data() {
    return {
      messageA: '',
      messageB: '',
      receivedMessageA: '',
      receivedMessageB: ''
    }
  },

  created() {
    // 监听来自组件B的消息
    EventBus.$on('B2A', (message) => {
      this.receivedMessageA = message
    })

    // 监听来自组件A的消息
    EventBus.$on('A2B', (message) => {
      this.receivedMessageB = message
    })
  },

  beforeDestroy() {
    // 清理事件监听
    EventBus.$off('B2A')
    EventBus.$off('A2B')
  },

  methods: {
    sendMessageA() {
      if (!this.messageA.trim()) return
      EventBus.$emit('A2B', this.messageA)
      this.messageA = ''
    },

    sendMessageB() {
      if (!this.messageB.trim()) return
      EventBus.$emit('B2A', this.messageB)
      this.messageB = ''
    }
  }
}
</script>

<style scoped>
.event-bus-demo {
  display: flex;
  gap: 20px;
}

.component-a, .component-b {
  flex: 1;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
}

.component-content {
  padding: 10px;
  background: #fff;
  border-radius: 4px;
}

h4 {
  margin: 0 0 10px 0;
  color: #606266;
}

.el-input {
  margin-top: 10px;
}
</style> 